// miniprogram/pages/summary/summary.js
import {
  wxp
}
from '../../util/wxp'
import {
  format
} from '../../util/index'
import Toast from '@vant/weapp/toast/toast'
const db = wx.cloud.database()

Page({
  mixins: [require('../../mixins/pageMixins')],
  /**
   * 页面的初始数据
   */
  data: {
    end: false,
    activeName: [],
    peopleCount: 0,
    errCount: 0,
    csCount: 0,
    calendarConfig: {
      theme: 'elegant',
      defaultDay: true,
      showLunar: true,
      highlightToday: true,
      disableLaterDay: true, // 是否禁选当天之后的日期
    },
    results: [],
    communities: [],
    buildingNoList: [],
    unitNoList: [],
    form: {
      pageNo: 1,
      pageSize: 20,
      community: null,
      buildingNo: null,
      unitNo: null,
      roomNo: null,
      keyword: null,
      date: format(new Date(), 'yyyy-MM-dd')
    }
  },
  onPullDownRefresh() {
    this.initData()
    wx.stopPullDownRefresh()
  },
  async onLoad() {
    await this.initData()
  },
  async initData() {
    wx.showLoading({
      title: '努力加载中...',
    })
    const {
      data
    } = await db.collection('community').where({
      status: 0
    }).get()
    const communities = data.map(c => {
      return {
        text: c.name,
        value: c._id,
        data: c
      }
    })
    communities.splice(0, 0, {
      text: '所有小区',
      value: null
    })
    this.setData({
      communities
    })
    // 自动设置
    if (communities.length > 1) {
      this.onCommChange({
        detail: communities[1].value,
        currentTarget: {
          dataset: {
            filed: 'community'
          }
        }
      })
    } else {
      this.updateBuilding([])
    }
    wx.hideLoading()
  },
  async onCommChange(e) {
    this.onFiledChange(e)
    if (e.detail) {
      // 后去所有楼栋
      const {
        list
      } = await db.collection('user').aggregate()
        .match({
          'baseInfo.community': e.detail
        })
        .group({
          '_id': '$baseInfo.buildingNo'
        }).end()
      this.updateBuilding(list)
    } else {
      this.updateBuilding([])
    }
    this.search(true)
  },
  updateBuilding(list) {
    const buildingNoList = []
    buildingNoList.push({
      text: '所有楼栋',
      value: null
    })
    list.forEach(item => {
      buildingNoList.push({
        text: item._id,
        value: item._id
      })
    })

    this.setData({
      'form.buildingNo': null,
      buildingNoList
    })
    this.updateUnit([])
  },
  async onBoChange(e) {
    this.onFiledChange(e)
    if (e.detail) {
      // 后去所有楼栋
      const {
        list
      } = await db.collection('user').aggregate()
        .match({
          'baseInfo.community': this.data.form.community,
          'baseInfo.buildingNo': e.detail
        })
        .group({
          '_id': '$baseInfo.unitNo'
        }).end()
      this.updateUnit(list)
    } else {
      this.updateUnit([])
    }
    this.search(true)
  },
  updateUnit(list) {
    const unitNoList = []
    unitNoList.push({
      text: '所有单元',
      value: null
    })
    list.forEach(item => {
      unitNoList.push({
        text: item._id,
        value: item._id
      })
    })
    this.setData({
      unitNoList,
      'form.unitNo': null
    })
  },
  onUoChange(e) {
    this.onFiledChange(e)
    this.search(true)
  },
  onSearch({
    detail
  }) {
    this.setData({
      'form.keyword': detail
    })
    this.search(true)
  },
  convertResult(results) {
    results.forEach(res => {
      res.errCount = res.records.filter(r => {
        if (r.tempValue && r.tempValue >= 37) {
          return true
        }
        return false
      }).length
      res.checkCount = (new Set(res.records.filter(r => r.tempValue).map(r => r.homemate))).size
      return res
    })
  },
  async search(newSearch) {
    wx.showLoading({
      title: '努力加载中...',
    })
    if (newSearch) {
      this.setData({
        'form.pageNo': 1,
        end: false,
        results: []
      })
    }
    const {
      result
    } = await wxp.cloud.callFunction({
      name: 'getSummary',
      data: this.data.form
    })
    this.setData({
      peopleCount: result.peopleCount,
      errCount: result.errCount,
      csCount: result.csCount,
    })
    this.convertResult(result.list)
    if (result.list.length == 0) {
      if (!newSearch) {
        Toast({
          message: '已经到底啦！',
          position: 'bottom'
        })
        this.setData({
          end: true
        })
      } else {
        this.setData({
          results: []
        })
      }
    } else {
      if (newSearch) {
        this.setData({
          results: result.list
        })
      } else {
        this.data.results.push(...result.list)
        this.setData({
          results: this.data.results
        })
      }
    }
    wx.hideLoading()
  },
  afterCalendarRender() {
    this.calendar.switchView('week')
  },
  onClikcToday(e) {
    this.calendar.jump({
      year: 2019,
      month: 12,
      day: 1
    });
  },
  afterTapDay({
    detail
  }) {
    const newDate = new Date(`${detail.year}-${detail.month}-${detail.day}`)
    this.setData({
      'form.date': format(newDate, 'yyyy-MM-dd')
    })
    this.search(true)
  },
  onReachBottom() {
    if (this.data.end) {
      return
    }
    this.setData({
      'form.pageNo': this.data.form.pageNo + 1
    })
    this.search(false)
  },
  onChange(e) {
    this.setData({
      activeNames: e.detail
    });
  },
  getRecordById(id) {
    for (let i = 0; i < this.data.results.length; ++i) {
      for (let j = 0; j < this.data.results[i].records.length; ++j) {
        if (this.data.results[i].records[j]._id == id) {
          return this.data.results[i].records[j]
        }
      }
    }
    return this.data.originRecords.filter(e => e._id == id)[0]
  },
  onViewRecord(e) {
    const id = e.currentTarget.dataset.id
    const date = this.data.form.date
    wx.navigateTo({
      url: `/pages/record/record?date=${date}&_id=${id}&from=summary`
    })
  }
})